<template>
  <el-form label-width="80px" :rules="rule" :model="user">
    <el-form-item label="姓名" prop="realName" class="is-required">
      <el-input v-model.trim="user.realName" />
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model.trim="user.email" />
    </el-form-item>
    <el-form-item label="手机号" prop="phone">
      <el-input v-model.trim="user.phone" />
    </el-form-item>
    <el-form-item label="简介" prop="phone">
      <el-input v-model.trim="user.description" type="textarea" :autosize="{minRows:8}" />
    </el-form-item>
    <el-form-item>
      <el-button v-loading="saving" type="primary" @click="submit">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import store from '@/store'
import { changeUserInfo } from '@/api/user'
import { fastMaxLen, fastNotBlank, validator } from '@/utils/form'

export default {
  props: {
    user: {
      type: Object,
      default: () => {
        return {
          realName: null,
          email: null,
          sex: null,
          superiorName: null,
          description: null,
          phone: null
        }
      }
    }
  },
  data() {
    return {
      saving: false
    }
  },
  computed: {
    rule() {
      return {
        realName: [
          fastNotBlank('请输入姓名'),
          fastMaxLen('姓名', 40)
        ],
        email: [
          { validator: validator('email_empty'), message: '请输入正确的邮箱', trigger: ['blur', 'change'] },
          { validator: validator('maxLen', 50), message: '邮箱长度最大50', trigger: ['blur', 'change'] }
        ],
        phone: [
          { validator: validator('phone_empty'), message: '手机号格式不正确', trigger: ['blur', 'change'] },
          { validator: validator('maxLen', 20), message: '手机号长度最大20', trigger: ['blur', 'change'] }
        ],
        description: [
          { validator: validator('maxLen', 100), message: '简介长度最大100', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    submit() {
      this.saving = true
      changeUserInfo(this.user).then((r) => {
        console.log(r)
        this.saving = false
        this.$message.success('保存成功')
        store.commit('SET_NAME', this.user.realName)
      }).catch(() => {
        this.saving = false
      })
    }
  }
}
</script>
